/* eslint-disable @typescript-eslint/camelcase */
const merge = require('webpack-merge')
const path = require('path')
const tsImportPluginFactory = require('ts-import-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const env = process.env.NODE_ENV === 'production'
const buildEnv = process.env.VUE_APP_PRODUCTION_ENV === 'prod'
console.log('请求域名：', process.env.VUE_APP_COM_API, process.env.VUE_APP_PRODUCTION_ENV)
module.exports = {
  lintOnSave: true,
  publicPath: env ? './' : '/',
  devServer: {
    proxy: {
      '/cweb': {
        target: 'http://localhost:3000/',
        changeOrigin: true
        // ws: true,
        // secure: false
        // pathRewrite: {
        //   '^/cweb': '/cweb'
        // }
      }
    }
  },
  productionSourceMap: !env, // SourceMap
  parallel: !env, // 结决打包时vant样式错乱
  configureWebpack: {
    resolve: {
      alias: {
        '@styles': path.join(__dirname, 'src/assets/styles'),
        '@images': path.join(__dirname, 'src/assets/images'),
        '@utils': path.join(__dirname, 'src/utils'),
        '@components': path.join(__dirname, 'src/components'),
        '@api': path.join(__dirname, 'src/serve/api')
      }
    },
    module: {
      rules: []
    },
    plugins: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            warnings: false,
            drop_console: buildEnv,
            drop_debugger: buildEnv,
            pure_funcs: ['console.log']
          }
        }
      })
    ],
    optimization: {
      // 提取公共
      splitChunks: {
        cacheGroups: {
          vendor: {
            chunks: 'initial',
            test: /node_modules/,
            name: 'vendor',
            maxInitialRequests: 5,
            priority: 100
          },
          common: {
            chunks: 'initial',
            test: /[\\/]src[\\/]js[\\/]/,
            name: 'common',
            minChunks: 2,
            maxInitialRequests: 5,
            priority: 60
          },
          styles: {
            name: 'styles',
            test: /\.(sa|sc|c|le)ss$/,
            chunks: 'initial',
            enforce: true
          },
          runtimeChunk: {
            name: 'manifest'
          }
        }
      }
    }
  },
  chainWebpack: config => {
    // console.log(config.plugin('fork-ts-checker'), 'plugins')
    // 指定type检测文件
    config.plugin('fork-ts-checker').tap(args => {
      args[0].reportFiles = ['src/**/*.{ts,tsx,vue}']
      return args
    })
    config.module
      .rule('ts')
      .use('ts-loader')
      .tap(options => {
        options = merge(options, {
          transpileOnly: true,
          getCustomTransformers: () => ({
            before: [
              tsImportPluginFactory({
                libraryName: 'vant',
                libraryDirectory: 'es',
                style: true
              })
            ]
          }),
          compilerOptions: {
            module: 'es2015'
          }
        })
        return options
      })
  }
}
